cmake_minimum_required(VERSION 3.7.2)

if(NOT PRODUCT)
    message(FATAL_ERROR "PRODUCT is what?")
endif()

project(${PRODUCT} LANGUAGES ASM C)

# Set project dir, so just projec can include this cmake file!!!
get_filename_component(PROJECT_PATH ../../ ABSOLUTE)
set(PROJECT_BINARY_DIR "${PROJECT_PATH}/tools/build")
# set(PROJECT_DIST_DIR   "${parent_dir}/dist")
message(STATUS "PROJECT_PATH:${PROJECT_PATH}")

#add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../app/vc/schedimp/ schedimp)
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/${PRODUCT}.cmake)
# Call CMakeLists.txt
# todo 需要优化，将全局搜索替换成在指定的目录范围内搜索

# 定义一个函数来递归搜索模块路径
function(find_module_paths_with_cmakelists search_dir module_name output_var)
    # 初始化结果列表
    set(result_list "")
    # 递归查找所有匹配模块名的目录
     execute_process(
         COMMAND find ${PROJECT_PATH} -type d -name ${module_name} -not -path "${PROJECT_PATH}/*zephyr*"
         OUTPUT_VARIABLE out_puts
         OUTPUT_STRIP_TRAILING_WHITESPACE
     )

    # 将输出转换为 CMake 列表（按换行符分割）
    string(REPLACE "\n" ";" module_dirs "${out_puts}")

    # 遍历所有找到的目录
    foreach(dir ${module_dirs})
        # 检查是否是目录（因为 GLOB_RECURSE 可能返回文件）
        if(IS_DIRECTORY ${dir})
            # 检查目录中是否存在 CMakeLists.txt
            if(EXISTS "${dir}/CMakeLists.txt")
                # 将路径转换为规范形式（去掉多余的 ./ 和 ../）
                get_filename_component(normalized_dir "${dir}" ABSOLUTE)
                # 添加到结果列表
                list(APPEND result_list "${normalized_dir}")
            endif()
        endif()
    endforeach()
    
    # 移除重复路径（如果有）
    list(REMOVE_DUPLICATES result_list)
    
    # 返回结果
    set(${output_var} ${result_list} PARENT_SCOPE)
endfunction()

foreach(componet ${componets})
     message("get componet: " ${componet})
    if(UNIX)   
        find_module_paths_with_cmakelists("${PROJECT_PATH}" "${componet}" FOUND_PATH)
        list(APPEND FOUND_PATHS ${FOUND_PATH})
    elseif(WIN32)
        MESSAGE("not support win yet")
    endif()
endforeach()

foreach(componet_path ${FOUND_PATHS})
    get_filename_component(componet_name "${componet_path}" NAME)
    add_subdirectory(${componet_path} ${componet_name})
endforeach()
